/**
 * 重构后的接口调用中间层
 * 基于uni.request封装，提供统一的API调用接口
 * 使用模块化控制器替代复杂的SQLite API调用逻辑
 * 支持请求/响应拦截器、错误处理、loading管理等功能
 * 支持Mock数据模拟
 */

import mockHandler from '../mock/index'
import { controllers, getController } from '../sqlite/controllers/index'
import config from '../config/index'

// 默认配置
const DEFAULT_CONFIG = {
  baseURL: config.api.baseURL,
  timeout: 10000,
  header: {
    'Content-Type': 'application/json'
  },
  showLoading: true,
  loadingText: '加载中...',
  showError: true,
  useMock: config.api.useMock || false, // 是否使用Mock数据
  dataSource: config.api.dataSource || 'remote' // 数据源类型
}

// 请求状态码映射
const STATUS_CODE = {
  SUCCESS: 200,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  SERVER_ERROR: 500,
  NETWORK_ERROR: -1
}

// 错误消息映射
const ERROR_MESSAGES = {
  [STATUS_CODE.UNAUTHORIZED]: '登录已过期，请重新登录',
  [STATUS_CODE.FORBIDDEN]: '没有权限访问',
  [STATUS_CODE.NOT_FOUND]: '请求的资源不存在',
  [STATUS_CODE.SERVER_ERROR]: '服务器内部错误',
  [STATUS_CODE.NETWORK_ERROR]: '网络连接失败，请检查网络设置',
  'timeout': '请求超时，请稍后重试',
  'default': '请求失败，请稍后重试'
}

// API路径到控制器方法的映射（支持增强路径匹配）
const API_MAPPING = {
  // 用户相关 - 基础路径
  'POST /v1/auth/login': { controller: 'user', method: 'login' },
  'POST /v1/auth/register': { controller: 'user', method: 'register' },
  'GET /v1/user/profile': { controller: 'user', method: 'getProfile' },
  'PUT /v1/user/profile': { controller: 'user', method: 'updateProfile' },
  
  // 用户相关 - 参数化路径
  'GET /v1/users/:id': { controller: 'user', method: 'getUserDetail' },
  'PUT /v1/users/:id': { controller: 'user', method: 'updateUser' },
  'DELETE /v1/users/:id': { controller: 'user', method: 'deleteUser' },
  'GET /v1/users/:id/avatar': { controller: 'user', method: 'getUserAvatar' },
  'POST /v1/users/:id/avatar': { controller: 'user', method: 'uploadAvatar' },
  
  // 习惯相关
  'GET /v1/habits': { controller: 'habits', method: 'getList' },
  'POST /v1/habits': { controller: 'habits', method: 'create' },
  'GET /v1/habits/:id': { controller: 'habits', method: 'getDetail' },
  'PUT /v1/habits/:id': { controller: 'habits', method: 'update' },
  'DELETE /v1/habits/:id': { controller: 'habits', method: 'delete' },
  'POST /v1/habits/:id/complete': { controller: 'habits', method: 'complete' },
  'DELETE /v1/habits/:id/complete': { controller: 'habits', method: 'uncomplete' },
  'GET /v1/habits/:id/history': { controller: 'habits', method: 'history' },
  'GET /v1/habits/stats': { controller: 'habits', method: 'stats' },
  
  // 待办事项相关
  'GET /v1/todos': { controller: 'todos', method: 'getList' },
  'POST /v1/todos': { controller: 'todos', method: 'create' },
  'GET /v1/todos/:id': { controller: 'todos', method: 'getDetail' },
  'PUT /v1/todos/:id': { controller: 'todos', method: 'update' },
  'DELETE /v1/todos/:id': { controller: 'todos', method: 'delete' },
  'POST /v1/todos/:id/complete': { controller: 'todos', method: 'complete' },
  'DELETE /v1/todos/:id/complete': { controller: 'todos', method: 'uncomplete' },
  'GET /v1/todos/today': { controller: 'todos', method: 'getTodayTodos' },
  'GET /v1/todos/overdue': { controller: 'todos', method: 'getOverdueTodos' },
  'GET /v1/todos/search': { controller: 'todos', method: 'search' },
  'POST /v1/todos/batch': { controller: 'todos', method: 'batchOperation' },
  'GET /v1/todos/stats': { controller: 'todos', method: 'getStats' },
  
  // 财务相关
  'GET /v1/finance/accounts': { controller: 'finance', method: 'getAccounts' },
  'POST /v1/finance/accounts': { controller: 'finance', method: 'createAccount' },
  'GET /v1/finance/accounts/:id': { controller: 'finance', method: 'getAccountDetail' },
  'PUT /v1/finance/accounts/:id': { controller: 'finance', method: 'updateAccount' },
  'DELETE /v1/finance/accounts/:id': { controller: 'finance', method: 'deleteAccount' },
  'GET /v1/finance/transactions': { controller: 'finance', method: 'getTransactions' },
  'POST /v1/finance/transactions': { controller: 'finance', method: 'createTransaction' },
  'GET /v1/finance/transactions/:id': { controller: 'finance', method: 'getTransactionDetail' },
  'PUT /v1/finance/transactions/:id': { controller: 'finance', method: 'updateTransaction' },
  'DELETE /v1/finance/transactions/:id': { controller: 'finance', method: 'deleteTransaction' },
  'GET /v1/finance/stats': { controller: 'finance', method: 'getStats' },
  'GET /v1/finance/budget': { controller: 'finance', method: 'getBudget' },
  'POST /v1/finance/budget': { controller: 'finance', method: 'setBudget' },
  
  // 时间管理相关
  'GET /v1/time/records': { controller: 'time', method: 'getRecords' },
  'POST /v1/time/records': { controller: 'time', method: 'createRecord' },
  'GET /v1/time/records/:id': { controller: 'time', method: 'getRecordDetail' },
  'PUT /v1/time/records/:id': { controller: 'time', method: 'updateRecord' },
  'DELETE /v1/time/records/:id': { controller: 'time', method: 'deleteRecord' },
  'POST /v1/time/timer/start': { controller: 'time', method: 'startTimer' },
  'POST /v1/time/timer/stop': { controller: 'time', method: 'stopTimer' },
  'POST /v1/time/timer/pause': { controller: 'time', method: 'pauseTimer' },
  'POST /v1/time/timer/resume': { controller: 'time', method: 'resumeTimer' },
  'GET /v1/time/timer/current': { controller: 'time', method: 'getCurrentTimer' },
  'GET /v1/time/activities': { controller: 'time', method: 'getActivities' },
  'POST /v1/time/activities': { controller: 'time', method: 'createActivity' },
  'PUT /v1/time/activities/:id': { controller: 'time', method: 'updateActivity' },
  'DELETE /v1/time/activities/:id': { controller: 'time', method: 'deleteActivity' },
  'GET /v1/time/stats': { controller: 'time', method: 'getStats' },
  
  // 设置相关
  'GET /v1/settings': { controller: 'settings', method: 'getSettings' },
  'PUT /v1/settings': { controller: 'settings', method: 'updateSettings' },
  'DELETE /v1/settings/:key': { controller: 'settings', method: 'deleteSetting' },
  'GET /v1/settings/notifications': { controller: 'settings', method: 'getNotificationSettings' },
  'PUT /v1/settings/notifications': { controller: 'settings', method: 'updateNotificationSettings' },
  'GET /v1/notifications': { controller: 'settings', method: 'getNotifications' },
  'PUT /v1/notifications/:id/read': { controller: 'settings', method: 'markNotificationRead' },
  'DELETE /v1/notifications/:id': { controller: 'settings', method: 'deleteNotification' },
  'POST /v1/data/export': { controller: 'settings', method: 'exportData' },
  'POST /v1/data/import': { controller: 'settings', method: 'importData' },
  'GET /v1/data/export/:taskId': { controller: 'settings', method: 'getExportStatus' },
  'POST /v1/data/reset': { controller: 'settings', method: 'resetData' },
  
  // 文件上传相关
  'POST /v1/upload/files': { controller: 'upload', method: 'uploadFile' },
  'GET /v1/upload/files': { controller: 'upload', method: 'getFileList' },
  'GET /v1/upload/files/:id': { controller: 'upload', method: 'getFileDetail' },
  'PUT /v1/upload/files/:id': { controller: 'upload', method: 'updateFile' },
  'DELETE /v1/upload/files/:id': { controller: 'upload', method: 'deleteFile' },
  'GET /v1/upload/files/:id/download': { controller: 'upload', method: 'downloadFile' },
  'DELETE /v1/upload/files/batch': { controller: 'upload', method: 'batchDeleteFiles' },
  'GET /v1/upload/stats': { controller: 'upload', method: 'getStats' },
  'GET /v1/upload/search': { controller: 'upload', method: 'searchFiles' },
  'GET /v1/upload/recent': { controller: 'upload', method: 'getRecentFiles' },
  'POST /v1/upload/cleanup': { controller: 'upload', method: 'cleanupExpiredFiles' },
  
  // 统计相关
  'GET /v1/stats/dashboard': { controller: 'stats', method: 'getDashboardStats' },
  'GET /v1/stats/habits': { controller: 'stats', method: 'getHabitsStats' },
  'GET /v1/stats/todos': { controller: 'stats', method: 'getTodosStats' },
  'GET /v1/stats/finance': { controller: 'stats', method: 'getFinanceStats' },
  'GET /v1/stats/time': { controller: 'stats', method: 'getTimeStats' },
  'GET /v1/stats/productivity': { controller: 'stats', method: 'getProductivityReport' },
  
  // 高级路径模式示例（展示增强匹配功能）
  
  // 嵌套资源路径
  'GET /v1/users/:userId/habits/:habitId': { controller: 'habits', method: 'getUserHabitDetail' },
  'PUT /v1/users/:userId/habits/:habitId': { controller: 'habits', method: 'updateUserHabit' },
  'DELETE /v1/users/:userId/habits/:habitId': { controller: 'habits', method: 'deleteUserHabit' },
  'GET /v1/users/:userId/habits/:habitId/records': { controller: 'habits', method: 'getUserHabitRecords' },
  'POST /v1/users/:userId/habits/:habitId/records': { controller: 'habits', method: 'createUserHabitRecord' },
  
  // 组织层级路径
  'GET /v1/organizations/:orgId/projects/:projectId/tasks': { controller: 'tasks', method: 'getProjectTasks' },
  'POST /v1/organizations/:orgId/projects/:projectId/tasks': { controller: 'tasks', method: 'createProjectTask' },
  'GET /v1/organizations/:orgId/projects/:projectId/tasks/:taskId': { controller: 'tasks', method: 'getProjectTaskDetail' },
  
  // 通配符路径（单级匹配）
  'GET /v1/files/*/download': { controller: 'upload', method: 'downloadFile' },
  'GET /v1/files/*/preview': { controller: 'upload', method: 'previewFile' },
  'POST /v1/webhooks/*/callback': { controller: 'webhook', method: 'handleCallback' },
  'GET /v1/search/*': { controller: 'search', method: 'globalSearch' },
  
  // 双通配符路径（多级匹配）
  'GET /v1/admin/**/logs': { controller: 'admin', method: 'getLogs' },
  'DELETE /v1/cache/**/clear': { controller: 'cache', method: 'clearCache' },
  'GET /v1/export/**': { controller: 'export', method: 'exportData' },
  'POST /v1/import/**': { controller: 'import', method: 'importData' },
  
  // 版本化API路径
  'GET /v:version/habits': { controller: 'habits', method: 'getListVersioned' },
  'GET /v:version/users/:id': { controller: 'user', method: 'getUserDetailVersioned' },
  
  // RESTful 资源集合操作
  'GET /v1/:resource': { controller: 'generic', method: 'getResourceList' },
  'POST /v1/:resource': { controller: 'generic', method: 'createResource' },
  'GET /v1/:resource/:id': { controller: 'generic', method: 'getResourceDetail' },
  'PUT /v1/:resource/:id': { controller: 'generic', method: 'updateResource' },
  'DELETE /v1/:resource/:id': { controller: 'generic', method: 'deleteResource' }
}

class RequestManager {
  constructor() {
    this.config = { ...DEFAULT_CONFIG }
    this.requestInterceptors = []
    this.responseInterceptors = []
    this.loadingCount = 0
  }

  /**
   * 设置全局配置
   * @param {Object} config 配置对象
   */
  setConfig(config) {
    this.config = { ...this.config, ...config }
  }

  /**
   * 添加请求拦截器
   * @param {Function} fulfilled 成功回调
   * @param {Function} rejected 失败回调
   */
  addRequestInterceptor(fulfilled, rejected) {
    this.requestInterceptors.push({ fulfilled, rejected })
  }

  /**
   * 添加响应拦截器
   * @param {Function} fulfilled 成功回调
   * @param {Function} rejected 失败回调
   */
  addResponseInterceptor(fulfilled, rejected) {
    this.responseInterceptors.push({ fulfilled, rejected })
  }

  /**
   * 显示loading
   * @param {String} title loading文本
   */
  showLoading(title = '加载中...') {
    if (this.loadingCount === 0) {
      uni.showLoading({
        title,
        mask: true
      })
    }
    this.loadingCount++
  }

  /**
   * 隐藏loading
   */
  hideLoading() {
    this.loadingCount--
    if (this.loadingCount <= 0) {
      this.loadingCount = 0
      uni.hideLoading()
    }
  }

  /**
   * 显示错误提示
   * @param {String} message 错误消息
   */
  showError(message) {
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    })
  }

  /**
   * 处理请求拦截器
   * @param {Object} config 请求配置
   * @returns {Object} 处理后的配置
   */
  async processRequestInterceptors(config) {
    let processedConfig = config
    
    for (const interceptor of this.requestInterceptors) {
      try {
        if (interceptor.fulfilled) {
          processedConfig = await interceptor.fulfilled(processedConfig)
        }
      } catch (error) {
        console.error('请求拦截器错误:', error);
        if (interceptor.rejected) {
          return interceptor.rejected(error)
        }
        throw error
      }
    }
    
    return processedConfig
  }

  /**
   * 处理响应拦截器
   * @param {Object} response 响应对象
   * @returns {Object} 处理后的响应
   */
  async processResponseInterceptors(response) {
    let processedResponse = response
    
    for (const interceptor of this.responseInterceptors) {
      try {
        if (interceptor.fulfilled) {
          processedResponse = await interceptor.fulfilled(processedResponse)
        }
      } catch (error) {
        if (interceptor.rejected) {
          return interceptor.rejected(error)
        }
        console.error('响应拦截器错误:', error);
        throw error
      }
    }
    
    return processedResponse
  }

  /**
   * 获取错误消息
   * @param {Number|String} code 错误码
   * @returns {String} 错误消息
   */
  getErrorMessage(code) {
    return ERROR_MESSAGES[code] || ERROR_MESSAGES.default
  }

  /**
   * 增强的路径匹配函数（借鉴Mock系统的智能匹配机制）
   * 支持参数化路径、查询参数、通配符等高级匹配模式
   * @param {String} pattern API路径模式
   * @param {String} path 实际路径
   * @returns {Object|null} 匹配结果，包含路径参数
   */
  matchPath(pattern, path) {
    // 移除查询参数进行匹配
    const cleanPath = path.split('?')[0]
    const cleanPattern = pattern.split('?')[0]
    
    const patternParts = cleanPattern.split('/').filter(part => part !== '')
    const pathParts = cleanPath.split('/').filter(part => part !== '')
    
    // 长度不匹配且没有通配符，直接返回null
    if (patternParts.length !== pathParts.length && !pattern.includes('*')) {
      return null
    }
    
    const params = {}
    let patternIndex = 0
    let pathIndex = 0
    
    while (patternIndex < patternParts.length && pathIndex < pathParts.length) {
      const patternPart = patternParts[patternIndex]
      const pathPart = pathParts[pathIndex]
      
      if (patternPart === '*') {
        // 通配符匹配剩余所有路径
        params['*'] = pathParts.slice(pathIndex).join('/')
        break
      } else if (patternPart === '**') {
        // 双通配符匹配多级路径
        const remainingPattern = patternParts.slice(patternIndex + 1)
        if (remainingPattern.length === 0) {
          params['**'] = pathParts.slice(pathIndex).join('/')
          break
        }
        // 复杂的双通配符匹配逻辑
        const matchResult = this.matchWildcardPath(remainingPattern, pathParts.slice(pathIndex))
        if (matchResult) {
          Object.assign(params, matchResult.params)
          params['**'] = matchResult.wildcardMatch
          break
        } else {
          return null
        }
      } else if (patternPart.startsWith(':')) {
        // 参数匹配
        const paramName = patternPart.slice(1)
        
        // 支持参数类型验证（如 :id(\\d+) 只匹配数字）
        if (paramName.includes('(') && paramName.includes(')')) {
          const [name, regexStr] = paramName.split('(')
          const regex = new RegExp('^' + regexStr.slice(0, -1) + '$')
          if (!regex.test(pathPart)) {
            return null
          }
          params[name] = pathPart
        } else {
          params[paramName] = pathPart
        }
      } else if (patternPart !== pathPart) {
        // 精确匹配失败
        return null
      }
      
      patternIndex++
      pathIndex++
    }
    
    // 检查是否完全匹配
    if (patternIndex === patternParts.length && pathIndex === pathParts.length) {
      return { params }
    }
    
    return null
  }
  
  /**
   * 处理双通配符的复杂匹配逻辑
   * @param {Array} remainingPattern 剩余的模式部分
   * @param {Array} remainingPath 剩余的路径部分
   * @returns {Object|null} 匹配结果
   */
  matchWildcardPath(remainingPattern, remainingPath) {
    // 简化实现：从后往前匹配
    if (remainingPattern.length > remainingPath.length) {
      return null
    }
    
    const matchLength = remainingPattern.length
    const wildcardLength = remainingPath.length - matchLength
    
    if (wildcardLength < 0) {
      return null
    }
    
    const wildcardMatch = remainingPath.slice(0, wildcardLength).join('/')
    const tailPath = remainingPath.slice(wildcardLength)
    
    // 验证尾部是否匹配
    for (let i = 0; i < matchLength; i++) {
      const pattern = remainingPattern[i]
      const path = tailPath[i]
      
      if (pattern.startsWith(':')) {
        // 参数匹配，这里简化处理
        continue
      } else if (pattern !== path) {
        return null
      }
    }
    
    return {
      wildcardMatch,
      params: {} // 这里可以进一步解析尾部的参数
    }
  }
  
  /**
   * 解析API路径参数（保持向后兼容）
   * @param {String} pattern API路径模式
   * @param {String} path 实际路径
   * @returns {Object} 解析出的参数
   */
  parsePathParams(pattern, path) {
    const matchResult = this.matchPath(pattern, path)
    return matchResult ? matchResult.params : {}
  }

  /**
   * 增强的API路径匹配函数
   * 支持精确匹配、参数化匹配、通配符匹配等多种模式
   * @param {String} method HTTP方法
   * @param {String} path 请求路径
   * @returns {Object|null} 匹配的API配置
   */
  matchApiPath(method, path) {
    const upperMethod = method.toUpperCase()
    const exactKey = `${upperMethod} ${path}`
    
    // 1. 精确匹配（最高优先级）
    if (API_MAPPING[exactKey]) {
      return { 
        ...API_MAPPING[exactKey], 
        pathParams: {},
        matchType: 'exact'
      }
    }
    
    // 2. 参数化匹配
    const parameterizedMatches = []
    const wildcardMatches = []
    
    for (const [pattern, config] of Object.entries(API_MAPPING)) {
      const [patternMethod, patternPath] = pattern.split(' ', 2)
      
      if (patternMethod !== upperMethod) {
        continue
      }
      
      const matchResult = this.matchPath(patternPath, path)
      if (matchResult) {
        const matchInfo = {
          ...config,
          pathParams: matchResult.params,
          pattern: patternPath,
          matchType: patternPath.includes('*') ? 'wildcard' : 'parameterized'
        }
        
        if (patternPath.includes('*')) {
          wildcardMatches.push(matchInfo)
        } else {
          parameterizedMatches.push(matchInfo)
        }
      }
    }
    
    // 3. 参数化匹配优先于通配符匹配
    if (parameterizedMatches.length > 0) {
      // 如果有多个匹配，选择最具体的（参数最少的）
      parameterizedMatches.sort((a, b) => {
        const aParamCount = Object.keys(a.pathParams).length
        const bParamCount = Object.keys(b.pathParams).length
        return aParamCount - bParamCount
      })
      return parameterizedMatches[0]
    }
    
    // 4. 通配符匹配
    if (wildcardMatches.length > 0) {
      // 选择最具体的通配符匹配
      wildcardMatches.sort((a, b) => {
        const aSpecificity = a.pattern.split('/').filter(p => !p.includes('*')).length
        const bSpecificity = b.pattern.split('/').filter(p => !p.includes('*')).length
        return bSpecificity - aSpecificity
      })
      return wildcardMatches[0]
    }
    
    return null
  }
  
  /**
   * 查找API处理器（统一的路由解析器）
   * @param {String} method HTTP方法
   * @param {String} url 请求URL
   * @param {Object} queryParams 查询参数
   * @returns {Object|null} API处理器配置
   */
  findApiHandler(method, url, queryParams = {}) {
    // 移除baseURL前缀
    let path = url.replace(this.config.baseURL, '')
    
    // 移除开头的斜杠
    if (path.startsWith('/')) {
      path = path.substring(1)
    }
    
    // 分离路径和查询参数
    const [cleanPath, queryString] = path.split('?')
    
    // 解析查询参数
    const urlParams = {}
    if (queryString) {
      queryString.split('&').forEach(param => {
        const [key, value] = param.split('=')
        if (key) {
          urlParams[decodeURIComponent(key)] = decodeURIComponent(value || '')
        }
      })
    }
    
    // 合并查询参数
    const allParams = { ...queryParams, ...urlParams }
    
    // 匹配API路径
    const apiConfig = this.matchApiPath(method, cleanPath)
    
    if (apiConfig) {
      return {
        ...apiConfig,
        queryParams: allParams,
        fullParams: { ...apiConfig.pathParams, ...allParams }
      }
    }
    
    return null
  }

  /**
   * 处理SQLite请求（使用增强的控制器路由系统）
   * @param {Object} config 请求配置
   * @returns {Promise} SQLite响应
   */
  async handleSqliteRequest(config) {
    try {
      // 显示loading
      if (config.showLoading) {
        this.showLoading(config.loadingText)
      }

      const method = config.method.toUpperCase()
      const data = config.data || {}
      
      // 使用增强的API处理器查找功能
      const apiHandler = this.findApiHandler(method, config.url, data)
      
      if (!apiHandler) {
        throw new Error(`API路径未找到: ${method} ${config.url}`)
      }
      
      // 获取控制器实例
      const controller = getController(apiHandler.controller)
      
      if (!controller) {
        throw new Error(`控制器未找到: ${apiHandler.controller}`)
      }
      
      // 检查控制器方法是否存在
      if (typeof controller[apiHandler.method] !== 'function') {
        throw new Error(`控制器方法未找到: ${apiHandler.controller}.${apiHandler.method}`)
      }
      
      // 智能参数准备（支持多种参数传递模式）
      const methodParams = this.prepareMethodParams(apiHandler, data)
      
      // 调用控制器方法
      const result = await controller[apiHandler.method](...methodParams)
      
      // 隐藏loading
      if (config.showLoading) {
        this.hideLoading()
      }

      // 构造响应对象
      const response = {
        data: result,
        statusCode: 200,
        header: {
          'content-type': 'application/json'
        },
        config,
        apiHandler // 附加API处理器信息用于调试
      }

      // 处理响应拦截器
      return await this.processResponseInterceptors(response)
      
    } catch (error) {
      // 隐藏loading
      if (config.showLoading) {
        this.hideLoading()
      }

      // 处理SQLite错误
      const sqliteError = {
        message: error.message || 'SQLite请求失败',
        code: 500,
        response: {
          data: {
            code: 500,
            message: error.message || 'SQLite请求失败'
          },
          statusCode: 500,
          header: {
            'content-type': 'application/json'
          }
        },
        config
      }

      if (config.showError) {
        this.showError(sqliteError.message)
      }

      throw sqliteError
    }
  }
  
  /**
   * 智能准备控制器方法参数
   * 根据API配置和数据自动组织参数
   * @param {Object} apiHandler API处理器配置
   * @param {Object} data 请求数据
   * @returns {Array} 方法参数数组
   */
  prepareMethodParams(apiHandler, data) {
    const methodParams = []
    const { pathParams, queryParams, fullParams } = apiHandler
    
    // 1. 处理路径参数（按常见模式排序）
    const commonPathParams = ['id', 'taskId', 'userId', 'fileId', 'accountId']
    
    for (const paramName of commonPathParams) {
      if (pathParams[paramName]) {
        methodParams.push(pathParams[paramName])
      }
    }
    
    // 2. 处理其他路径参数
    for (const [paramName, paramValue] of Object.entries(pathParams)) {
      if (!commonPathParams.includes(paramName)) {
        methodParams.push(paramValue)
      }
    }
    
    // 3. 处理请求体数据
    if (data && Object.keys(data).length > 0) {
      // 过滤掉已经作为路径参数的数据
      const filteredData = { ...data }
      Object.keys(pathParams).forEach(key => {
        delete filteredData[key]
      })
      
      if (Object.keys(filteredData).length > 0) {
        methodParams.push(filteredData)
      }
    }
    
    // 4. 处理查询参数（如果需要）
    if (queryParams && Object.keys(queryParams).length > 0) {
      // 某些方法可能需要查询参数作为单独的参数
      const relevantQueryParams = { ...queryParams }
      
      // 移除时间戳等系统参数
      delete relevantQueryParams._t
      delete relevantQueryParams.timestamp
      
      if (Object.keys(relevantQueryParams).length > 0) {
        methodParams.push(relevantQueryParams)
      }
    }
    
    return methodParams
  }

  /**
   * 处理Mock请求
   * @param {Object} config 请求配置
   * @returns {Promise} Mock响应
   */
  async handleMockRequest(config) {
    try {
      // 显示loading
      if (config.showLoading) {
        this.showLoading(config.loadingText)
      }

      // 构造Mock请求路径
      const mockPath = config.url.replace(config.baseURL, '')
      const mockKey = `${config.method.toUpperCase()} ${mockPath}`
      
      // 调用Mock处理器
      const mockResponse = await mockHandler.mockRequest(mockPath, config.method, config.data)
      
      // 如果Mock处理器返回null，说明没有对应的Mock数据
      if (mockResponse === null) {
        throw new Error(JSON.stringify({
          code: 404,
          message: `Mock数据未找到: ${mockKey}`
        }))
      }
      
      const mockData = mockResponse.data

      // 隐藏loading
      if (config.showLoading) {
        this.hideLoading()
      }

      // 构造响应对象
      const response = {
        data: {
          code: 200,
          message: 'success',
          data: mockData
        },
        statusCode: 200,
        header: {
          'content-type': 'application/json'
        },
        config
      }

      // 处理响应拦截器
      return await this.processResponseInterceptors(response)
      
    } catch (error) {
      // 隐藏loading
      if (config.showLoading) {
        this.hideLoading()
      }

      // 处理Mock错误
      let errorData
      try {
        errorData = JSON.parse(error.message)
      } catch {
        errorData = {
          code: 500,
          message: error.message || 'Mock请求失败'
        }
      }

      const mockError = {
        message: errorData.message,
        code: errorData.code,
        response: {
          data: errorData,
          statusCode: errorData.code >= 400 ? errorData.code : 500,
          header: {
            'content-type': 'application/json'
          }
        },
        config
      }

      if (config.showError) {
        this.showError(mockError.message)
      }

      throw mockError
    }
  }

  /**
   * 处理网络请求
   * @param {Object} config 请求配置
   * @returns {Promise} 网络响应
   */
  async handleNetworkRequest(config) {
    return new Promise((resolve, reject) => {
      // 显示loading
      if (config.showLoading) {
        this.showLoading(config.loadingText)
      }

      uni.request({
        ...config,
        success: (response) => {
          // 隐藏loading
          if (config.showLoading) {
            this.hideLoading()
          }

          // 处理响应拦截器
          this.processResponseInterceptors(response)
            .then(resolve)
            .catch(reject)
        },
        fail: (error) => {
          // 隐藏loading
          if (config.showLoading) {
            this.hideLoading()
          }

          // 处理网络错误
          const networkError = {
            message: this.getErrorMessage(error.errMsg || 'default'),
            code: STATUS_CODE.NETWORK_ERROR,
            response: {
              data: {
                code: STATUS_CODE.NETWORK_ERROR,
                message: error.errMsg || '网络请求失败'
              },
              statusCode: STATUS_CODE.NETWORK_ERROR,
              header: {}
            },
            config
          }

          if (config.showError) {
            this.showError(networkError.message)
          }

          reject(networkError)
        }
      })
    })
  }

  /**
   * 发起请求
   * @param {Object} options 请求选项
   * @returns {Promise} 请求响应
   */
  async request(options) {
    // 合并配置
    const config = {
      ...this.config,
      ...options,
      header: {
        ...this.config.header,
        ...options.header
      }
    }

    try {
      // 处理请求拦截器
      const processedConfig = await this.processRequestInterceptors(config)

      // 根据数据源类型选择处理方式
      if (processedConfig.dataSource === 'sqlite') {
        return await this.handleSqliteRequest(processedConfig)
      } else if (processedConfig.useMock) {
        return await this.handleMockRequest(processedConfig)
      } else {
        return await this.handleNetworkRequest(processedConfig)
      }
    } catch (error) {
      console.error('请求错误:', error);
      throw error
    }
  }

  /**
   * GET请求
   * @param {String} url 请求地址
   * @param {Object} params 请求参数
   * @param {Object} options 请求选项
   * @returns {Promise} 请求响应
   */
  get(url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params,
      ...options
    })
  }

  /**
   * POST请求
   * @param {String} url 请求地址
   * @param {Object} data 请求数据
   * @param {Object} options 请求选项
   * @returns {Promise} 请求响应
   */
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  /**
   * PUT请求
   * @param {String} url 请求地址
   * @param {Object} data 请求数据
   * @param {Object} options 请求选项
   * @returns {Promise} 请求响应
   */
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  /**
   * DELETE请求
   * @param {String} url 请求地址
   * @param {Object} params 请求参数
   * @param {Object} options 请求选项
   * @returns {Promise} 请求响应
   */
  delete(url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data: params,
      ...options
    })
  }

  /**
   * 上传文件
   * @param {String} url 上传地址
   * @param {String} filePath 文件路径
   * @param {Object} formData 表单数据
   * @param {Object} options 请求选项
   * @returns {Promise} 上传响应
   */
  upload(url, filePath, formData = {}, options = {}) {
    const config = {
      ...this.config,
      ...options
    }

    return new Promise((resolve, reject) => {
      // 显示loading
      if (config.showLoading) {
        this.showLoading(config.loadingText || '上传中...')
      }

      uni.uploadFile({
        url: config.baseURL + url,
        filePath,
        name: 'file',
        formData,
        header: config.header,
        success: (response) => {
          // 隐藏loading
          if (config.showLoading) {
            this.hideLoading()
          }

          try {
            const data = JSON.parse(response.data)
            resolve({
              data,
              statusCode: response.statusCode,
              header: response.header,
              config
            })
          } catch (error) {
            reject({
              message: '响应数据解析失败',
              code: STATUS_CODE.SERVER_ERROR,
              response,
              config
            })
          }
        },
        fail: (error) => {
          // 隐藏loading
          if (config.showLoading) {
            this.hideLoading()
          }

          const uploadError = {
            message: this.getErrorMessage(error.errMsg || 'default'),
            code: STATUS_CODE.NETWORK_ERROR,
            response: error,
            config
          }

          if (config.showError) {
            this.showError(uploadError.message)
          }

          reject(uploadError)
        }
      })
    })
  }
}

// 创建请求管理器实例
const requestManager = new RequestManager()

// 添加默认请求拦截器
requestManager.addRequestInterceptor(
  (config) => {
    // 添加时间戳防止缓存
    if (config.method === 'GET') {
      const separator = config.url.includes('?') ? '&' : '?'
      config.url += `${separator}_t=${Date.now()}`
    }
    
    // 添加用户token（如果存在）
    const token = uni.getStorageSync('token')
    if (token) {
      config.header.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加默认响应拦截器
requestManager.addResponseInterceptor(
  (response) => {
    // 统一处理响应数据
    const { data, statusCode } = response
    
    if (statusCode === STATUS_CODE.SUCCESS) {
      // 检查业务状态码
      if (data && data.code !== undefined) {
        if (data.code === 0 || data.code === 200) {
          return response
        } else {
          // 业务错误
          const businessError = {
            message: data.message || '业务处理失败',
            code: data.code,
            response,
            config: response.config
          }
          
          // 特殊处理登录过期
          if (data.code === STATUS_CODE.UNAUTHORIZED) {
            // 清除本地存储的用户信息
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            
            // 跳转到登录页
            uni.reLaunch({
              url: '/pages/auth/login'
            })
          }
          
          return Promise.reject(businessError)
        }
      }
    } else {
      // HTTP状态码错误
      const httpError = {
        message: requestManager.getErrorMessage(statusCode),
        code: statusCode,
        response,
        config: response.config
      }
      
      return Promise.reject(httpError)
    }
    
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 导出请求方法
export default {
  request: requestManager.request.bind(requestManager),
  get: requestManager.get.bind(requestManager),
  post: requestManager.post.bind(requestManager),
  put: requestManager.put.bind(requestManager),
  delete: requestManager.delete.bind(requestManager),
  upload: requestManager.upload.bind(requestManager),
  setConfig: requestManager.setConfig.bind(requestManager),
  addRequestInterceptor: requestManager.addRequestInterceptor.bind(requestManager),
  addResponseInterceptor: requestManager.addResponseInterceptor.bind(requestManager)
}